//
//  ScanQRCodeVC.swift
//  MIFI
//
//  Created by 金嗓子卡卡 on 2019/4/17.
//  Copyright © 2019 NJMifi. All rights reserved.
//

import UIKit
import SGQRCode
import SVProgressHUD

class ScanQRCodeVC: RootVC {
    
    var scanSuccess : ((String,String)->())?
    private let config = SGQRCodeObtainConfigure()
    private let obtain = SGQRCodeObtain()
    
    private lazy var scanView: SGQRCodeScanView = {
        let view = SGQRCodeScanView(frame: CGRect(x: 0, y: naviView!.bottom, width: screenWidth, height: screenHeight))
        view.scanAnimationStyle = ScanAnimationStyleDefault
        view.cornerLocation = CornerLoactionOutside
        view.cornerColor = themeColor
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func configView() {
        configNaviView(title: "Scan Code")
        view.addSubview(scanView)
        
        obtain.establishQRCodeObtainScan(with: self, configure: config)
        obtain.setBlockWithQRCodeObtainScanResult {[weak self] (obtain, result) in
            if result != nil {
                self!.checkResult(result: result!)
            }
        }
        obtain.startRunningWith(before: {
            
        }) {
            
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        scanView.addTimer()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        scanView.removeTimer()
    }
    
    private func checkResult(result:String) {
        let arr = result.components(separatedBy: ";")
        guard arr.count > 2 else {
//            SVProgressHUD.showError(withStatus: "")
            return
        }
        let name = arr[1].components(separatedBy: ":")
        guard name.count > 1 || name[0] == "S" else {
//            SVProgressHUD.showError(withStatus: "无效的二维码")
            return
        }
        
        let password = arr[2].components(separatedBy: ":")
        guard password.count > 1 || password[0] == "P" else {
//            SVProgressHUD.showError(withStatus: "无效的二维码")
            return
        }
        
        if scanSuccess != nil {
            scanSuccess!(name[1],password[1])
        }
        
    }
    
    deinit {
        scanView.removeTimer()
        scanView.removeFromSuperview()
    }
    
}
